<template>
  <j-modal :title="'销售订单 - ' + title" :width="width" :visible="visible" :maskClosable="false" :keyboard="false"
    draggable switchFullscreen :okButtonProps="{ class: { 'jee-hidden': disableSubmit } }" @cancel="handleCancel">

    <template slot="footer">
      <!-- <a-button v-if="disableSubmit" key="print" @click="handlePrint" style="margin-right: 48px">打印</a-button> -->
      <a-button @click="handleCancel" :type="action === 'detail' ? 'primary' : ''">{{ action === 'detail' ? '关闭' : '取消'
      }}</a-button>
      <!-- <a-button v-if="!disableSubmit" key="save" @click="handleSave" type="primary">保存</a-button> -->
      <a-button v-if="!disableSubmit" key="submit" @click="handleOrderSubmit()" type="primary">确定</a-button>
      <a-button v-if="action === 'check'" key="check" @click="handleOrderCheckSubmit()" type="primary">提交</a-button>
    </template>
    <order-form ref="realForm" :initial-form="formData" :disabled="disableSubmit" @add="submitCallback"
      @edit="submitEdit" @cancel="handleCancel" @check="OrderCheckSubmit" />
   
  </j-modal>
</template>

<script>
import { postAction } from '@/api/manage'
// import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { OrderModalMixin } from '../../common/mixins/OrderModalMixin'
import orderForm from "./OrderForm.vue";

export default {
  name: 'OrderScaleModal',
  mixins: [OrderModalMixin],
  components: { orderForm },

  data() {
    return {
      width: 1300,
      formData: {}, // 父组件维护的表单数据（如从列表传递的编辑数据）
    }
  },
  methods: {
    submitCallback(orderData) {
      console.log('submitCallback', orderData);
      postAction('/wr/salOrderWr/add', orderData).then(res => {
        console.log('订单新增的res', res);
        // this.productOptions = res.result.productList;
        if (res.code == 200) {
          this.$message.success(res.message);
          this.$emit('refreshs');
          this.visible = false
        }else{
          this.$message.error(res.message);
        }
      });

    },
    submitEdit(orderData) {
      postAction('/wr/salOrderWr/edit', orderData).then(res => {
        console.log('订单编辑的', res);
        // this.productOptions = res.result.productList;
        if (res.code == 200) {
          this.$message.success(res.message);
          this.$emit('refreshs');
          this.visible = false

        }
      });

    },
    OrderCheckSubmit(orderData) {
      const transformedData = this.transformData(orderData);
      console.log('transformedData', transformedData);
      postAction('/wr/salOrderWr/submit', transformedData).then(res => {
        console.log('订单提交的', res);
        // this.productOptions = res.result.productList;
        if (res.code == 200) {
          this.$message.success(res.message);
          this.$emit('refreshs');
          this.visible = false

        } else {
          this.$message.error(res.message);
        }
      });
    },
  
 
    transformData(originalData) {
      // 后端接口需要的是一个数组
      const result = [];

      // 从原始数据中获取billNo作为salOrderWrOrderNo
      const salOrderWrOrderNo = originalData.billNo;

      // 遍历每个供应商
      if (originalData.supplierList && originalData.supplierList.length > 0) {
        originalData.supplierList.forEach(supplier => {
          // 创建供应商对应的主对象
          const supplierItem = {
            supplierId: supplier.supplierId || '',
            salOrderWrOrderId: supplier.salOrderWrId || '',  // 取自供应商的salOrderWrId
            salOrderWrOrderNo: salOrderWrOrderNo || '',      // 取自原始数据的billNo
            attachmentUrl: supplier.attachUrl || '',
            remark: supplier.remark || '',
            status: supplier.settleFlag || 0,  // 假设用settleFlag作为status

            // 处理detailsList
            detailsList: []
          };

          // 处理产品列表，转换为detailsList
          if (supplier.productList && supplier.productList.length > 0) {
            supplier.productList.forEach(product => {
              supplierItem.detailsList.push({
                productId: product.productId || '',
                qty: product.qty || 0,
                amount: product.qty * product.buyUnitAmount || 0,  // 计算金额
                currency: originalData.currency || '',  // 取自原始数据的currency
                status: 0  // 默认为0，可根据实际情况调整
              });
            });
          }

          result.push(supplierItem);
        });
      }

      return result;
    },

    // 示例用法：
    // const transformedData = transformData(originalData);
    // console.log(transformedData);

    openModal(row) {
      this.visible = true;
      if (row) { // 编辑场景：传递行数据给子组件
        this.action = 'edit';
        this.formData = { ...row };
      } else { // 新增场景：清空初始数据
        this.action = 'add';
        this.formData = {};
      }
    },
    onFormOk(formData) {
      // 子组件提交成功：关闭弹窗 + 通知祖父组件（如列表页刷新）
      this.visible = false;
      this.$emit('ok', formData); // 向祖父组件（如salesOrderList）传递结果
    },
    onFormError(error) {
      // 子组件提交失败：显示错误信息
      this.$message.error(error);
    },
    handleCancel() {
      this.visible = false;
      this.$refs.realForm.resetForm(); // 通知子组件重置表单
    },
    handleOrderSubmit() {
      // 调用子组件提交方法，处理成功/失败
      this.$refs.realForm.submitForm()
        .then(formData => {
          this.onFormOk(formData); // 复用成功处理逻辑
        })
        .catch(error => {
          this.onFormError(error); // 复用失败处理逻辑
        });
    },
    handleOrderCheckSubmit() {
      // 调用子组件提交方法，处理成功/失败
      this.$refs.realForm.submitForm()
        .then(formData => {
          this.onFormOk(formData); // 复用成功处理逻辑
        })
        .catch(error => {
          this.onFormError(error); // 复用失败处理逻辑
        });
    },
  }
}
</script>

<style scoped></style>
